package com.rybbaby.tss.platform.permission.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.*;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.platform.initializer.HandlePermissionsInitializer;
import com.rybbaby.tss.platform.initializer.MenuPermissionsInitializer;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import com.rybbaby.tss.platform.sysAdminUser.service.ISysAdminUserService;
import com.rybbaby.tss.platform.sysAdminUserJoinSysMenuPermissions.entity.SysAdminUserJoinSysMenuPermissions;
import com.rybbaby.tss.platform.sysAdminUserJoinSysMenuPermissions.service.ISysAdminUserJoinSysMenuPermissionsService;
import com.rybbaby.tss.platform.sysConfig.entity.SysConfig;
import com.rybbaby.tss.platform.sysConfig.service.ISysConfigService;
import com.rybbaby.tss.platform.sysConfigGroup.entity.SysConfigGroup;
import com.rybbaby.tss.platform.sysConfigGroup.service.ISysConfigGroupService;
import com.rybbaby.tss.platform.sysHandlePermissions.entity.SysHandlePermissions;
import com.rybbaby.tss.platform.sysHandlePermissions.service.ISysHandlePermissionsService;
import com.rybbaby.tss.platform.sysHandlePermissionsAttrs.entity.SysHandlePermissionsAttrs;
import com.rybbaby.tss.platform.sysHandlePermissionsAttrs.service.ISysHandlePermissionsAttrsService;
import com.rybbaby.tss.platform.sysHandlePermissionsClasses.entity.SysHandlePermissionsClasses;
import com.rybbaby.tss.platform.sysHandlePermissionsClasses.service.ISysHandlePermissionsClassesService;
import com.rybbaby.tss.platform.sysHandlePermissionsEvents.entity.SysHandlePermissionsEvents;
import com.rybbaby.tss.platform.sysHandlePermissionsEvents.service.ISysHandlePermissionsEventsService;
import com.rybbaby.tss.platform.sysHandlePermissionsStyles.entity.SysHandlePermissionsStyles;
import com.rybbaby.tss.platform.sysHandlePermissionsStyles.service.ISysHandlePermissionsStylesService;
import com.rybbaby.tss.platform.sysMenuPermissions.entity.SysMenuPermissions;
import com.rybbaby.tss.platform.sysMenuPermissions.service.ISysMenuPermissionsService;
import com.rybbaby.tss.platform.sysRole.entity.SysRole;
import com.rybbaby.tss.platform.sysRole.service.ISysRoleService;
import com.rybbaby.tss.platform.sysRoleGroup.service.ISysRoleGroupService;
import com.rybbaby.tss.platform.sysRoleJoinSysMenuPermissions.entity.SysRoleJoinSysMenuPermissions;
import com.rybbaby.tss.platform.sysRoleJoinSysMenuPermissions.service.ISysRoleJoinSysMenuPermissionsService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.BooleanUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 谢进伟
 * @description 权限设置控制层
 * @createDate 2016年11月3日 上午11:48:24
 */
@Controller
@RequestMapping(value = "permissionSetting")
public class PermissionSettingController extends BaseController {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysAdminUserService sysAdminUserService;
    @Autowired
    private ISysMenuPermissionsService sysMenuPermissionsService;
    @Autowired
    private ISysHandlePermissionsService sysHandlePermissionsService;
    @Autowired
    private ISysHandlePermissionsClassesService sysHandlePermissionsClassesService;
    @Autowired
    private ISysHandlePermissionsStylesService sysHandlePermissionsStylesService;
    @Autowired
    private ISysHandlePermissionsEventsService sysHandlePermissionsEventsService;
    @Autowired
    private ISysHandlePermissionsAttrsService sysHandlePermissionsAttrsService;
    @Autowired
    private ISysRoleJoinSysMenuPermissionsService sysRoleJoinSysMenuPermissionsService;
    @Autowired
    private ISysAdminUserJoinSysMenuPermissionsService sysAdminUserJoinSysMenuPermissionsService;
    @Autowired
    private ISysRoleGroupService sysRoleGroupService;
    @Autowired
    private ISysConfigGroupService sysConfigGroupService;
    @Autowired
    private ISysConfigService sysConfigService;

    @RequestLog(content = "获取角色列表")
    @RequestMapping(value = "roleList")
    public ModelAndView roleList(SysRole entity, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("roleListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysRole.class);
            String schoolId = this.getLoginUser().getSchoolId();
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            if (StringUtils.isNotBlank(schoolId)) {
                String sql = "select * from sys_role_group where code=?";
                Map<String, Object> roleGroupMap = this.sysRoleGroupService.findOneForJdbc(sql, new Object[]{schoolId});
                dc.add(Restrictions.eq("groupId", roleGroupMap.get("id") + ""));
            }
            dc.addOrder(Order.desc("createTime"));
            PageBean pageBean = sysRoleService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "显示菜单权限编辑界面")
    @RequestMapping(value = "showHandlePermissionsView")
    public ModelAndView showHandlePermissionsView(@RequestParam(required = true) String id, String menuPermissionId, Boolean copy) {
        ModelAndView mav = new ModelAndView("sysPage/platform/permission/editHandlePermission.html");
        try {
            SysHandlePermissions sysHandlePermissions = this.sysHandlePermissionsService.get(id);
            if (sysHandlePermissions == null) {
                sysHandlePermissions = new SysHandlePermissions();
                sysHandlePermissions.setMenuId(menuPermissionId);
                sysHandlePermissions.setIsForbidden(true);
                sysHandlePermissions.setWeight(1);
            }
            mav.addObject("bean", sysHandlePermissions);
            mav.addObject("copy", BooleanUtils.toBoolean(copy));
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取用户列表")
    @RequestMapping(value = "userList")
    public ModelAndView userList(SysAdminUser entity, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("userListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            String notFixedPageSize = getParameter("notFixedPageSize");
            if (StringUtils.isBlank(notFixedPageSize)) {
                paramPageBean.setPageSize(8);
            }
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysAdminUser.class);
            String schoolId = this.getLoginUser().getSchoolId();
            if (StringUtils.isNotBlank(schoolId)) {
                dc.add(Restrictions.eq("schoolId", schoolId));
            }
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysAdminUserService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取菜单操作权限列表")
    @RequestMapping(value = "handlePermissionList")
    public ModelAndView handlePermissionList(SysHandlePermissions entity, String containerId, String searchFormId, PageBean paramPageBean, @RequestParam(required = true) String menuPermissionId, @RequestParam(required = true) String objType, @RequestParam(required = true) String objId) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("handlePermissionListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(7);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
            dc.add(Restrictions.isNull("defaultHandlePermissionId"));
            dc.add(Restrictions.isNull("adminUserPermissionAllotId"));
            dc.add(Restrictions.isNull("rolePermissionAllotId"));
            dc.add(Restrictions.eq("menuId", menuPermissionId));
            entity.setMenuId(null);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("objType", objType);
            mav.addObject("objId", objId);
            mav.addObject("menuPermissionId", menuPermissionId);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", "sysHandlePermissionsController/saveOrUpdate.do");
            mav.addObject("deleteUrl", requestURI + "/deleteHandlePermission.do");
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo("search_" + searchFormId, containerId));
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取菜单操作权限分配界面")
    @RequestMapping(value = "loadNowMenuAllHandlePermissionAllot")
    public ModelAndView loadNowMenuAllHandlePermissionAllot(SysHandlePermissions entity, String containerId, String searchFormId, PageBean paramPageBean, @RequestParam(required = true) String menuPermissionId, @RequestParam(required = true) String objType, @RequestParam(required = true) String objId) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("loadNowMenuAllHandlePermissionAllotView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(5);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
            dc.add(Restrictions.isNull("defaultHandlePermissionId"));
            dc.add(Restrictions.isNull("adminUserPermissionAllotId"));
            dc.add(Restrictions.isNull("rolePermissionAllotId"));
            dc.add(Restrictions.eq("menuId", menuPermissionId));
            entity.setMenuId(null);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            List<SysHandlePermissions> nowMenuAllHandlePermission = this.sysHandlePermissionsService.findByDetached(dc);// 该菜单下所有的操作权限
            mav.addObject("nowMenuAllHandlePermission", nowMenuAllHandlePermission);
            if ("user".equals(objType)) {
                DetachedCriteria dc1 = DetachedCriteria.forClass(SysAdminUserJoinSysMenuPermissions.class);
                dc1.add(Restrictions.and(Restrictions.eq("adminUserId", objId), Restrictions.eq("menuPermissionId", menuPermissionId)));
                List<SysAdminUserJoinSysMenuPermissions> list = this.sysAdminUserJoinSysMenuPermissionsService.findByDetached(dc1);
                if (list != null && !list.isEmpty()) {
                    String allotId = list.get(0).getId();
                    DetachedCriteria dcForAlready = DetachedCriteria.forClass(SysHandlePermissions.class);
                    dcForAlready.add(Restrictions.eq("menuId", menuPermissionId));
                    dcForAlready.add(Restrictions.eq("adminUserPermissionAllotId", allotId));
                    dcForAlready.add(Restrictions.isNotNull("defaultHandlePermissionId"));
                    dcForAlready.add(Restrictions.isNull("rolePermissionAllotId"));
                    List<SysHandlePermissions> alreadyHaveHandlePremissions = this.sysHandlePermissionsService.findByDetached(dcForAlready);// 管理员已经拥有的操作权限
                    mav.addObject("alreadyHaveHandlePremissions", alreadyHaveHandlePremissions);

                }
            } else if ("role".equals(objType)) {
                DetachedCriteria dc2 = DetachedCriteria.forClass(SysRoleJoinSysMenuPermissions.class);
                dc2.add(Restrictions.and(Restrictions.eq("roleId", objId), Restrictions.eq("menuPermissionId", menuPermissionId)));
                List<SysRoleJoinSysMenuPermissions> list = this.sysRoleJoinSysMenuPermissionsService.findByDetached(dc2);
                if (list != null && !list.isEmpty()) {
                    String allotId = list.get(0).getId();
                    DetachedCriteria dcForAlready = DetachedCriteria.forClass(SysHandlePermissions.class);
                    dcForAlready.add(Restrictions.eq("menuId", menuPermissionId));
                    dcForAlready.add(Restrictions.eq("rolePermissionAllotId", allotId));
                    dcForAlready.add(Restrictions.isNotNull("defaultHandlePermissionId"));
                    dcForAlready.add(Restrictions.isNull("adminUserPermissionAllotId"));
                    List<SysHandlePermissions> alreadyHaveHandlePremissions = this.sysHandlePermissionsService.findByDetached(dcForAlready);// 当前角色已经拥有的操作权限
                    mav.addObject("alreadyHaveHandlePremissions", alreadyHaveHandlePremissions);
                }
            }
            mav.addObject("objType", objType);
            mav.addObject("objId", objId);
            mav.addObject("menuPermissionId", menuPermissionId);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @ResponseBody
    @RequestLog(content = "保存权限分配结果")
    @RequestMapping(value = "saveHandlePermissionAllot")
    public String saveHandlePermissionAllot(@RequestParam(required = true) String menuPermissionId, @RequestParam(required = true) String objType, @RequestParam(required = true) String objId) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            String[] handlePermissionIds = request.getParameterValues("handlePermissionId");
            Object loginUserId = getLoginUserId();
            List<SysHandlePermissions> alreadyHaveHandlePremissions = this.sysHandlePermissionsService.saveHandlePermissionAllot(menuPermissionId, objType, objId, handlePermissionIds, loginUserId == null ? null : loginUserId.toString());
            // 刷新缓存
            HandlePermissionsInitializer.reloadHandlePermission(alreadyHaveHandlePremissions);
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    @RequestLog(content = "获取操作权限class属性列表")
    @RequestMapping(value = "handlePermissionsClassesList")
    public ModelAndView handlePermissionsClassesList(SysHandlePermissionsClasses entity, @RequestParam(required = true) String handlePermissionId, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("handlePermissionsClassesListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(5);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissionsClasses.class);
            dc.add(Restrictions.eq("handlePermissionId", handlePermissionId));
            dc.addOrder(Order.asc("weight"));
            dc.addOrder(Order.desc("createTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsClassesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("handlePermissionId", handlePermissionId);
            mav.addObject("actionUrl", request.getRequestURI());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("saveUrl", "sysHandlePermissionsClassesController/saveOrUpdate.do");
            mav.addObject("deleteUrl", "sysHandlePermissionsClassesController/delete.do");
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取操作权限style内联样式列表")
    @RequestMapping(value = "handlePermissionsStyleList")
    public ModelAndView handlePermissionsStyleList(SysHandlePermissionsStyles entity, @RequestParam(required = true) String handlePermissionId, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("handlePermissionsStyleListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(5);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissionsStyles.class);
            dc.add(Restrictions.eq("handlePermissionId", handlePermissionId));
            dc.addOrder(Order.asc("weight"));
            dc.addOrder(Order.desc("createTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsStylesService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("handlePermissionId", handlePermissionId);
            mav.addObject("actionUrl", request.getRequestURI());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("saveUrl", "sysHandlePermissionsStylesController/saveOrUpdate.do");
            mav.addObject("deleteUrl", "sysHandlePermissionsStylesController/delete.do");
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取操作权限event设置列表")
    @RequestMapping(value = "handlePermissionsEventList")
    public ModelAndView handlePermissionsEventList(SysHandlePermissionsEvents entity, @RequestParam(required = true) String handlePermissionId, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("handlePermissionsEventListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(5);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissionsEvents.class);
            dc.add(Restrictions.eq("handlePermissionId", handlePermissionId));
            dc.addOrder(Order.asc("weight"));
            dc.addOrder(Order.desc("createTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsEventsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("handlePermissionId", handlePermissionId);
            mav.addObject("actionUrl", request.getRequestURI());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("saveUrl", "sysHandlePermissionsEventsController/saveOrUpdate.do");
            mav.addObject("deleteUrl", "sysHandlePermissionsEventsController/delete.do");
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @RequestLog(content = "获取操作权限event设置列表")
    @RequestMapping(value = "handlePermissionsAttrList")
    public ModelAndView handlePermissionsAttrList(SysHandlePermissionsAttrs entity, @RequestParam(required = true) String handlePermissionId, String containerId, String searchFormId, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("handlePermissionsAttrleListView"));
        try {
            if (StringUtils.isNotBlank(searchFormId)) {
                searchFormId = SequenceUtil.getUpperCaseUUID();
            }
            paramPageBean.setPageSize(5);
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissionsAttrs.class);
            dc.add(Restrictions.eq("handlePermissionId", handlePermissionId));
            dc.addOrder(Order.asc("weight"));
            dc.addOrder(Order.desc("createTime"));
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = sysHandlePermissionsAttrsService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", searchFormId);
            mav.addObject("containerId", containerId);
            mav.addObject("handlePermissionId", handlePermissionId);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("saveUrl", "sysHandlePermissionsAttrsController/saveOrUpdate.do");
            mav.addObject("deleteUrl", "sysHandlePermissionsAttrsController/delete.do");
            mav.addObject("pagingBar", pageBean.getPagingBarNoInfo(searchFormId, containerId));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * @param id 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "批量删除指定id的菜单操作权限对象")
    @RequestMapping(value = "deleteHandlePermission", method = RequestMethod.GET)
    public String deleteHandlePermission(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.sysHandlePermissionsService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    @ResponseBody
    @RequestLog(content = "获取菜单权限json串")
    @RequestMapping(value = "getMenuPermissions", method = RequestMethod.GET)
    public String getMenuPermissions() {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            StringBuffer data = new StringBuffer();
            data.append("[");
            String pId = getParameter("pId");// 父菜单id
            String checkedCallback = getParameter("checkedCallback");// 选中权限是的回调函数,该回调函数接收复选框对象
            String permissionDetail = getParameter("permissionDetailCallback");// 菜单权限详情回调函数,该回调函数接收菜单权限id
            String objType = getParameter("objType");// 设置对象类型
            String objId = getParameter("objId");// 设置对象Id
            DetachedCriteria dc = DetachedCriteria.forClass(SysMenuPermissions.class);
            dc.addOrder(Order.asc("weight"));
            if (StringUtils.isBlank(pId)) {// 所有顶级菜单权限
                dc.add(Restrictions.isNull("pId"));
                List<SysMenuPermissions> topMenuPermissions = this.sysMenuPermissionsService.findByDetached(dc);
                for (SysMenuPermissions smp : topMenuPermissions) {
                    data.append("{ name: \"").append(smp.getName()).append("\", type: \"" + "folder" + "\", params: ").append(JSONUtil.toJsonStr(smp));
                    data.append(",data: [");
                    data.append("]},");
                }
            } else {// 子菜单
                dc.add(Restrictions.eq("pId", pId));
                List<SysMenuPermissions> childrenMenuPermissions = this.sysMenuPermissionsService.findByDetached(dc);
                String sql = "SELECT COUNT(1) count FROM sys_menu_permissions WHERE pId=?";
                for (SysMenuPermissions smp : childrenMenuPermissions) {
                    // 复选框
                    StringBuffer checkbox = new StringBuffer();
                    checkbox.append("<div class='checkbox tree-checkbox'>");
                    checkbox.append("<label>");
                    checkbox.append("<input type='checkbox' class='inverted' ").append("  objId='").append(objId).append("' objType='").append(objType).append("' value=").append(smp.getId());
                    switch (objType) {
                        case "user":// 管理员私有权限自动选中
                            DetachedCriteria dc1 = DetachedCriteria.forClass(SysAdminUserJoinSysMenuPermissions.class);
                            dc1.add(Restrictions.and(Restrictions.eq("adminUserId", objId), Restrictions.eq("menuPermissionId", smp.getId())));
                            List<SysAdminUserJoinSysMenuPermissions> existsPermission = this.sysAdminUserJoinSysMenuPermissionsService.findByDetached(dc1);
                            if (existsPermission != null && !existsPermission.isEmpty()) {
                                checkbox.append(" checked ");
                            }
                            break;
                        case "role":// 角色权限自动选中
                            DetachedCriteria dc2 = DetachedCriteria.forClass(SysRoleJoinSysMenuPermissions.class);
                            dc2.add(Restrictions.and(Restrictions.eq("roleId", objId), Restrictions.eq("menuPermissionId", smp.getId())));
                            List<SysRoleJoinSysMenuPermissions> exists = this.sysRoleJoinSysMenuPermissionsService.findByDetached(dc2);
                            if (exists != null && !exists.isEmpty()) {
                                checkbox.append(" checked ");
                            }
                            break;
                    }
                    checkbox.append((StringUtils.isNotBlank(checkedCallback) ? (" onchange=" + checkedCallback + "(this)") : ""));
                    checkbox.append(">").append("<span class='text'>").append(smp.getName()).append("</span>");
                    checkbox.append("</label>");
                    checkbox.append("</div>");

                    // 判断是否存在下级菜单权限
                    Map<String, Object> map = this.sysMenuPermissionsService.findOneForJdbc(sql, new Object[]{smp.getId()});
                    boolean isHasChildren = map != null && !map.isEmpty() && Integer.parseInt(map.get("count").toString()) > 0;
                    data.append("{ name: \"").append(isHasChildren ? smp.getName() : checkbox.append("<div class='tree-actions aling-right'> <a class='btn btn-palegreen btn-xs' href='javascript:' onclick=(").append(permissionDetail).append("('").append(smp.getId()).append("','").append(objType).append("','").append(objId).append("','").append("'))>设置</a></div>")).append("\", type: \"").append(isHasChildren ? "folder" : "item").append("\", params: ").append(JSONUtil.toJsonStr(smp));
                    data.append(",data: [");
                    data.append("]},");
                }
            }
            if (data.length() > 1) {
                data.deleteCharAt(data.length() - 1);
            }
            data.append("]");
            ajr.setData(data);
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    @ResponseBody
    @RequestLog(content = "获取菜单权限nestable串")
    @RequestMapping(value = "getMenuPermissionsNestable", method = RequestMethod.GET)
    public String getMenuPermissionsNestable() {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            StringBuffer data = loadMenuPermission(null);
            if (StringUtils.isEmpty(data.toString())) {
                data.append("未找到菜单权限,请先添加菜单权限!");
            }
            ajr.setData(data);
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    /**
     * @param objType          设置对象(角色：role,用户：user)
     * @param objId            设置对象id
     * @param objId            角色id
     * @param menuPermissionId 菜单权限id
     * @param op               操作指标(true表示新增,false表示删除)
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "allotPermission")
    @RequestLog(content = "角色菜单权限分配")
    public String allotPermission(@RequestParam(required = true) String objType, @RequestParam(required = true) String objId, @RequestParam(required = true) String menuPermissionId, @RequestParam(required = true) Boolean op) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            Object loginUserIdObj = getLoginUserId();
            String loginUserId = loginUserIdObj != null ? loginUserIdObj.toString() : null;
            switch (objType) {
                case "user":// 管理员私有权限分配
                    if (op) {
                        DetachedCriteria dc = DetachedCriteria.forClass(SysAdminUserJoinSysMenuPermissions.class);
                        dc.add(Restrictions.and(Restrictions.eq("adminUserId", objId), Restrictions.eq("menuPermissionId", menuPermissionId)));
                        List<SysAdminUserJoinSysMenuPermissions> existsPermission = this.sysAdminUserJoinSysMenuPermissionsService.findByDetached(dc);
                        if (existsPermission == null || existsPermission.isEmpty()) {
                            SysAdminUserJoinSysMenuPermissions saujsmp = new SysAdminUserJoinSysMenuPermissions();
                            saujsmp.setAdminUserId(objId);
                            saujsmp.setMenuPermissionId(menuPermissionId);
                            saujsmp.setCreateUserId(loginUserId);
                            saujsmp.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            Serializable id = this.sysAdminUserJoinSysMenuPermissionsService.save(saujsmp);
                            if (id == null) {
                                ajr.setResCode(-1);
                                ajr.setResMsg("管理员私有菜单权限分配失败!");
                            }
                        }
                    } else {
                        String sql = "DELETE FROM sys_admin_user_join_sys_menu_permissions WHERE adminUserId=? AND menuPermissionId=?";
                        Integer row = this.sysRoleJoinSysMenuPermissionsService.executeSql(sql, new Object[]{objId, menuPermissionId});
                        if (row < 1) {
                            ajr.setResCode(-1);
                            ajr.setResMsg("移除管理员私有菜单权限记录失败!");
                        }
                    }
                    break;
                case "role":// 角色权限分配
                    if (op) {
                        DetachedCriteria dc = DetachedCriteria.forClass(SysRoleJoinSysMenuPermissions.class);
                        dc.add(Restrictions.and(Restrictions.eq("roleId", objId), Restrictions.eq("menuPermissionId", menuPermissionId)));
                        List<SysRoleJoinSysMenuPermissions> exists = this.sysRoleJoinSysMenuPermissionsService.findByDetached(dc);
                        if (exists == null || exists.isEmpty()) {
                            SysRoleJoinSysMenuPermissions srjsmp = new SysRoleJoinSysMenuPermissions();
                            srjsmp.setRoleId(objId);
                            srjsmp.setMenuPermissionId(menuPermissionId);
                            srjsmp.setCreateTime(new Timestamp(System.currentTimeMillis()));
                            srjsmp.setCreateUserId(loginUserId);
                            srjsmp.setWeight(1);
                            Serializable id = this.sysRoleJoinSysMenuPermissionsService.save(srjsmp);
                            if (id == null) {
                                ajr.setResCode(-1);
                                ajr.setResMsg("角色菜单权限分配失败!");
                            }
                        }
                    } else {
                        String sql = "DELETE FROM sys_role_join_sys_menu_permissions WHERE roleId=? AND menuPermissionsId=?";
                        Integer row = this.sysRoleJoinSysMenuPermissionsService.executeSql(sql, new Object[]{objId, menuPermissionId});
                        if (row < 1) {
                            ajr.setResCode(-1);
                            ajr.setResMsg("移除角色菜单权限分配记录失败!");
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    @RequestLog(content = "获取菜单权限信息")
    @RequestMapping(value = "getPermission")
    public ModelAndView getPermission(@RequestParam(required = true) String menuPermissionId) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("permissionDetaView"));
        try {
            SysMenuPermissions smp = this.sysMenuPermissionsService.get(menuPermissionId);
            // 名称数据源
            List<Map<String, Object>> pId_datasources = this.sysMenuPermissionsService.pIdDatasource();
            mav.addObject("pId_datasources", pId_datasources);
            mav.addObject("serializeNum", SequenceUtil.getOriginalUUID());
            mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdateMenuPermission.do");
            mav.addObject("smp", smp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mav;
    }

    /**
     * 保存编辑的菜单权限对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存编辑的菜单权限对象")
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdateMenuPermission", method = RequestMethod.POST)
    public String saveOrUpdateMenuPermission(SysMenuPermissions entity) {
        return this.sysMenuPermissionsService.saveOrUpdateMeenuPermission(entity, getLoginUserId());
    }

    /**
     * @param weightSortJson 排好序的json串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存菜单权限权重")
    @RequestMapping(value = "savePermissionWeight", method = RequestMethod.POST)
    public String savePermissionWeight(@RequestParam(required = true) String weightSortJson) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            List<Object[]> sortWeghtList = new ArrayList<Object[]>();
            Map<String, List<String>> referenceMap = new HashMap<String, List<String>>();
            if (StringUtils.isNotBlank(weightSortJson)) {
                referenceMap.put("root", new ArrayList<String>());
                JSONArray weightSortJsonArray = JSONArray.fromObject(weightSortJson);
                calcWeight(weightSortJsonArray, sortWeghtList, "root", referenceMap);
            }
            if (!sortWeghtList.isEmpty()) {
                if (!this.sysMenuPermissionsService.updateMenuPermissionWeight(sortWeghtList, referenceMap)) {
                    ajr.setResCode(500);
                    ajr.setResMsg("更新权限权重失败!");
                } else {
                    MenuPermissionsInitializer.load();
                }
            }
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 获取最后一层菜单
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAllMenus")
    public String getAllMenus() {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            DetachedCriteria dc = DetachedCriteria.forClass(SysMenuPermissions.class);
            dc.add(Restrictions.sqlRestriction(" (SELECT count(1) FROM sys_menu_permissions WHERE pId =this_.id)=0"));
            dc.add(Restrictions.isNotNull("pId"));
            List<SysMenuPermissions> lastLevelMenuPermissions = this.sysMenuPermissionsService.findByDetached(dc);
            List<SysMenuPermissions> lastLevelMenuPermissions1 = new ArrayList<>();
            copyMenuPermissions(lastLevelMenuPermissions, lastLevelMenuPermissions1);
            DetachedCriteria dc1 = DetachedCriteria.forClass(SysMenuPermissions.class);
            dc1.add(Restrictions.or(Restrictions.isNull("pId"), Restrictions.sqlRestriction(" (SELECT count(1) FROM sys_menu_permissions WHERE pId =this_.id)>0")));
            List<SysMenuPermissions> menuPermissions = this.sysMenuPermissionsService.findByDetached(dc1);
            List<SysMenuPermissions> menuPermissions1 = new ArrayList<>();
            copyMenuPermissions(menuPermissions, menuPermissions1);
            ajr.setData(menuPermissions1);
            ajr.addExtendParam("lastLevelMenuPermissions", lastLevelMenuPermissions1);
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }


    /**
     * 转到默认角色配置界面
     *
     * @return
     */
    @RequestMapping(value = "toDefaultRoleSettingView")
    public ModelAndView toDefaultRoleSettingView() {
        ModelAndView mav = new ModelAndView("sysPage/platform/permission/defaultMenuSetting.html");
        try {
            SysConfig tssSchoolDefaultRoleConfigJson = this.sysConfigService.findUniqueByProperty("name", "tssSchoolDefaultRoleConfigJson");
            mav.addObject("tssSchoolDefaultRoleConfigJson", tssSchoolDefaultRoleConfigJson);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 获取指定菜单下的所有操作权限
     *
     * @return
     */
    @RequestMapping(value = "getMenuHandlePermission")
    public ModelAndView getMenuHandlePermission(@RequestParam(required = true) String menuPermissionId) {
        ModelAndView mav = new ModelAndView("sysPage/platform/permission/defaultMenuSetting_setHandlePermission.html");
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(SysHandlePermissions.class);
            dc.add(Restrictions.isNull("defaultHandlePermissionId"));
            dc.add(Restrictions.isNull("adminUserPermissionAllotId"));
            dc.add(Restrictions.isNull("rolePermissionAllotId"));
            dc.add(Restrictions.eq("menuId", menuPermissionId));
            List<SysHandlePermissions> nowMenuAllHandlePermission = this.sysHandlePermissionsService.findByDetached(dc);// 该菜单下所有的操作权限
            mav.addObject("nowMenuAllHandlePermission", nowMenuAllHandlePermission);
            mav.addObject("menuPermissionId", menuPermissionId);
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    @ResponseBody
    @RequestMapping(value = "saveDefaultRoleConfig")
    public String saveDefaultRoleConfig(@RequestBody(required = true) String config) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            System.out.println(config);
            String tssConfigGroupName = "TSS参数";
            SysConfigGroup tssConfigGroup = this.sysConfigGroupService.findUniqueByProperty("groupName", tssConfigGroupName);
            if (tssConfigGroup == null) {
                SysConfigGroup sysConfigGroup = new SysConfigGroup();
                sysConfigGroup.setGroupName(tssConfigGroupName);
                sysConfigGroup.setRemark("TSS相关参数");
                sysConfigGroup.setCreateTime(new Timestamp(System.currentTimeMillis()));
                sysConfigGroup.setCreateUserId(this.getLoginUserId() + "");
                Serializable newGroupId = this.sysConfigGroupService.save(sysConfigGroup);
                if (newGroupId != null) {
                    tssConfigGroup.setId(newGroupId.toString());
                }
            }
            String groupId = tssConfigGroup.getId();
            if (groupId != null) {
                SysConfig tssSchoolDefaultRoleConfigJson = this.sysConfigService.findUniqueByProperty("name", "tssSchoolDefaultRoleConfigJson");
                if (tssSchoolDefaultRoleConfigJson == null) {
                    tssSchoolDefaultRoleConfigJson = new SysConfig();
                    tssSchoolDefaultRoleConfigJson.setCreateUserId(this.getLoginUserId() + "");
                    tssSchoolDefaultRoleConfigJson.setRemark("园所默认角色配置json");
                    tssSchoolDefaultRoleConfigJson.setName("tssSchoolDefaultRoleConfigJson");
                    tssSchoolDefaultRoleConfigJson.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    tssSchoolDefaultRoleConfigJson.setGroupId(groupId);
                    Serializable newConfigId = this.sysConfigService.save(tssSchoolDefaultRoleConfigJson);
                    tssSchoolDefaultRoleConfigJson.setId(newConfigId.toString());
                }
                SysConfig sysConfig = this.sysConfigService.get(tssSchoolDefaultRoleConfigJson.getId());
                sysConfig.setValue(config);
                this.sysConfigService.updateEntitiy(sysConfig);
                ajr.setResMsg("保存成功");
            } else {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败(参数分组设置失败!)");
            }
        } catch (Exception e) {
            ajr.setResMsg(e.getMessage());
            ajr.setResCode(500);
            e.printStackTrace();
        }
        return ajr.jsonResponse(true);
    }

    private void copyMenuPermissions(List<SysMenuPermissions> menuPermissions, List<SysMenuPermissions> menuPermissions1) {
        for (SysMenuPermissions lastLevelMenuPermission : menuPermissions) {
            SysMenuPermissions smp = new SysMenuPermissions();
            smp.setId(lastLevelMenuPermission.getId());
            smp.setpId(lastLevelMenuPermission.getpId());
            smp.setName(lastLevelMenuPermission.getName());
            menuPermissions1.add(smp);
        }
    }

    private void calcWeight(JSONArray weightSortJsonArray, List<Object[]> sortWeghtList, String parentId, Map<String, List<String>> referenceMap) {
        for (int i = 0, len = weightSortJsonArray.size(); i < len; i++) {
            List<Object> values = new ArrayList<Object>();
            JSONObject jsonObject = weightSortJsonArray.getJSONObject(i);
            String id = jsonObject.getString("id");
            values.add(i + 1);
            values.add(id);
            referenceMap.get(parentId).add(id);
            sortWeghtList.add(values.toArray());
            if (jsonObject.containsKey("children")) {
                referenceMap.put(id, new ArrayList<String>());
                calcWeight(jsonObject.getJSONArray("children"), sortWeghtList, id, referenceMap);
            }
        }
    }

    /**
     * 加载所有菜单权限
     *
     * @param pId 父菜单Id
     * @return
     */
    private StringBuffer loadMenuPermission(String pId) {
        StringBuffer data = new StringBuffer();
        DetachedCriteria dc = DetachedCriteria.forClass(SysMenuPermissions.class);
        dc.addOrder(Order.asc("weight"));
        if (StringUtils.isBlank(pId)) {// 所有顶级菜单权限
            dc.add(Restrictions.isNull("pId"));
            List<SysMenuPermissions> topMenuPermissions = this.sysMenuPermissionsService.findByDetached(dc);
            data.append("<ol class=\"dd-list\">");
            for (SysMenuPermissions smp : topMenuPermissions) {
                data.append("<li class=\"dd-item bordered-inverse\" data-id=\"").append(smp.getId()).append("\">");
                data.append("<div class=\"dd-handle\">");
                data.append(smp.getName());
                data.append("</div>");
                data.append(loadMenuPermission(smp.getId()));
                data.append("</li>");
            }
            data.append("</ol>");
        } else {// 子菜单
            dc.add(Restrictions.eq("pId", pId));
            List<SysMenuPermissions> childrenMenuPermissions = this.sysMenuPermissionsService.findByDetached(dc);
            if (childrenMenuPermissions != null && !childrenMenuPermissions.isEmpty()) {
                String sql = "SELECT COUNT(1) count FROM sys_menu_permissions WHERE pId=?";
                data.append("<ol class=\"dd-list\" style=\"\">");
                for (SysMenuPermissions smp : childrenMenuPermissions) {
                    // 判断是否存在下级菜单权限
                    Map<String, Object> map = this.sysMenuPermissionsService.findOneForJdbc(sql, new Object[]{smp.getId()});
                    boolean isHasChildren = map != null && !map.isEmpty() && Integer.parseInt(map.get("count").toString()) > 0;
                    data.append("<li class=\"dd-item bordered-inverse").append(!isHasChildren ? "dd-collapsed" : "").append("\" data-id=\"").append(smp.getId()).append("\">");
                    data.append("<div class=\"dd-handle\">");
                    data.append(smp.getName());
                    data.append("</div>");
                    if (isHasChildren) {
                        data.append(loadMenuPermission(smp.getId()));
                    }
                    data.append("</li>");
                }
                data.append("</ol>");
            }
        }
        return data;
    }
}
